package com.mdp.workflow.re.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.BaseUtils;
import com.mdp.core.utils.RequestUtils;
import com.mdp.qx.HasRole;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.mdp.workflow.re.entity.Procdef;
import com.mdp.workflow.re.service.ProcdefService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.io.IOUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.RepositoryService;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value="/**/re/procdef")
@Api(tags={"act_re_procdef-操作接口"})
public class ProcdefController {
	
	static Logger logger =LoggerFactory.getLogger(ProcdefController.class);
	
	@Autowired
	private ProcdefService procdefService;

	@Autowired
	RepositoryService repositoryService;

	@Value(value = "${mdp.platform-branch-id:platform-branch-001}")
	String platformBranchId;

	@ApiOperation( value = "act_re_procdef-查询列表",notes=" ")
	@ApiEntityParams(Procdef.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=Procdef.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listProcdef(@ApiIgnore @RequestParam Map<String,Object> params){
		try {
			User user=LoginUtils.getCurrentUserInfo();
			RequestUtils.transformArray(params, "categoryIds");
			RequestUtils.transformArray(params, "tagIds");
			QueryWrapper<Procdef> qw = QueryTools.initQueryWrapper(Procdef.class , params).in("tenant_id_",platformBranchId,user.getBranchId());;
			IPage page=QueryTools.initPage(params);
			params.put("platformBranchId",platformBranchId);
			params.put("branchId",user.getBranchId());
			List<Map<String,Object>> datas = procdefService.selectListMapByWhere(page,qw,params);
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}

	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 */
	@RequestMapping(value="/categorys")
	public Result selectCategorys( @RequestParam Map<String,Object> procdef){
		User user=LoginUtils.getCurrentUserInfo();
		List<String>	categorys = procdefService.selectCategorys(Arrays.asList(user.getBranchId(), platformBranchId));	//列出Procdef列表

		return Result.ok().setData(categorys.stream().map(k-> BaseUtils.map("id",k,"name",k)));
	}

	/**
	 * 根据主键挂起流程模型
	 */

	@HasRole(roles= {"flowAdmin","platformAdmin"})
	@RequestMapping(value="/suspend")
	public Result suspend(@RequestBody com.mdp.workflow.re.entity.Procdef procdef) {

		try{
			procdefService.suspend(procdef);
			return Result.ok();
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}

	/**
	 * 根据主键激活模型
	 */

	@HasRole(roles= {"flowAdmin","platformAdmin"})
	@RequestMapping(value="/activate")
	public Result activate(@RequestBody com.mdp.workflow.re.entity.Procdef procdef) {

		try{
			procdefService.activate(procdef);
			return Result.ok();
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}

	/**
	 * 获得流程图的流
	 * @param processDefinitionId
	 * @return
	 */
	@RequestMapping(value="/diagram/{processDefinitionId}", method = RequestMethod.GET)
	public void getProcessDefinitionDiagram(@PathVariable String processDefinitionId, HttpServletResponse response){
		try {
			BpmnModel bpmnModel = this.repositoryService.getBpmnModel(processDefinitionId);
			InputStream is = new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel, "png", Collections.<String>emptyList(), Collections.<String>emptyList(),"宋体", "宋体",  "宋体", null, 1.0, false);
			IOUtils.copy(is, response.getOutputStream());
		} catch (IOException e) {
			logger.error("",e);
		}
	}

}
